package com.maxsalad.baidu.service;

import com.maxsalad.baidu.entity.RequestCmd;
import com.maxsalad.baidu.entity.order.detail.ResponseOrderDetailEntity;
import com.maxsalad.baidu.entity.order.list.ResponseOrderListEntity;
import com.maxsalad.common.util.JsonUtil;
import com.maxsalad.common.util.OkHttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 2014-400 on 2016-03-07.
 */
@Service(value = "baiduOrderService")
public class OrderService extends BaseService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    /**
     * 获取订单列表
     *
     * @param startTime 开始时间(秒)
     * @param end_time  结束时间(秒)
     * @param status    多个英文都好隔开1:待确认, 5-已确认,7	正在取餐,8-正在配送,9-已完成,10-已取消
     * @param page      页码从1开始
     * @return
     * @throws Exception
     */
    public ResponseOrderListEntity getOrderList(long startTime, long end_time, String status, int page) throws Exception {
        Map param = new HashMap();
        param.put("start_time", startTime);
        param.put("end_time", end_time);
        param.put("status", status);
        param.put("page", page);

        RequestCmd cmd = new RequestCmd();
        cmd.setCmd("order.list");
        cmd.setSource(getSource());
        cmd.setSecret(getSecret());
        cmd.setTimestamp((int) (System.currentTimeMillis() / 1000L));
        cmd.setTicket(UUID.randomUUID().toString().toUpperCase());
        cmd.setBody(param);

        String sign = getSign(cmd);
        cmd.setSign(sign);

        String json = OkHttpUtil.post(getBaseUrl(), JsonUtil.serialize(cmd));
        log.debug(json);

        return (ResponseOrderListEntity) JsonUtil.deserialize(json, ResponseOrderListEntity.class);
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单ID
     * @return
     * @throws Exception
     */
    public ResponseOrderDetailEntity getOrderDetail(String orderId) throws Exception {
        Map param = new HashMap();
        param.put("order_id", orderId);

        RequestCmd cmd = new RequestCmd();
        cmd.setCmd("order.get");
        cmd.setSource(getSource());
        cmd.setSecret(getSecret());
        cmd.setTimestamp((int) (System.currentTimeMillis() / 1000L));
        cmd.setTicket(UUID.randomUUID().toString().toUpperCase());
        cmd.setBody(param);

        String sign = getSign(cmd);
        cmd.setSign(sign);

        String json = OkHttpUtil.post(getBaseUrl(), JsonUtil.serialize(cmd));
        log.debug(json);

        return (ResponseOrderDetailEntity) JsonUtil.deserialize(json, ResponseOrderDetailEntity.class);
    }
}
